# coding: UTF-8

from django.contrib.auth import logout
from django.contrib.auth.admin import User
from django.contrib.contenttypes.models import ContentType
from django.db.models import get_model
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, redirect
from senbzblog.blog.models import Article, Category, Page, History
from senbzblog.comments.forms import CommentForm
#from senbzblog.index.index import search_process
from senbzblog.tags.models import TaggedItem, Tag
from senbzblog.utils import utils
from senbzblog.utils.utils import login_post, render_response

MONTH_ALIAS = ['Jan.', 'Feb.', 'March', 'April', 'May', 'June', 'July', 'Aug.', 'Sep.', 'Oct.', 'Nov.', 'Dec.']

def show_blog_home(request, username):
    #显示公共信息
    member = get_object_or_404(User, username=username)
    blog = member.bloginfo
    base_ctx = get_base_context(member, blog)
    
    ctx = {}
    ctx.update(base_ctx)
    return render_response(request, "themes/%s/blog_home.html" % (blog.theme), ctx)

def show_article_list(request, username):
    #显示公共信息
    member = get_object_or_404(User, username=username)
    blog = member.bloginfo
    base_ctx = get_base_context(member, blog)
    
    #显示分页后的文章
    current_page = utils.get_current_page(request)
    article_list = Article.objects.filter(blog=blog)
    # 获取分页信息
    pages_context = utils.get_pages_context(article_list, current_page, blog.display_count)
    articles = pages_context['page_current']
    articles_page_range = pages_context['page_range']
    
    #显示文章存档
    archives = article_list.dates('created_date', 'month')
    year_list = get_different_years(archives)
    
    ctx = {'articles':articles, 'articles_page_range':articles_page_range,
           'archives':archives, 'year_list':year_list}
    ctx.update(base_ctx)
    return render_response(request, "themes/%s/blog_article_list.html" % (blog.theme), ctx)

def show_article_detail(request, username, slug):
    #显示公共信息
    member = get_object_or_404(User, username=username)
    blog = member.bloginfo
    base_ctx = get_base_context(member, blog)
    
    #显示文章
    article = get_object_or_404(Article.objects, blog=blog, slug=slug, is_published=True)
    request.session['a'] = 1
    History.add_history(article, request.META['REMOTE_ADDR'], request.user, request.session._session_key)
    current_category = article.category.id
    root_category = article.category.get_root_category()
    
    #发送评论后要跳转到的页面
    nexturl = article.get_absolute_url()
    #显示该文章的标签
    ctype = ContentType.objects.get_for_model(article)
    tag_items = TaggedItem.objects.filter(content_type__pk=ctype.pk, object_pk=article.pk)
    
    ctx = {'article':article, 'nexturl':nexturl, 'tag_items':tag_items, 'root_category':root_category,
           'current_category':current_category}
    ctx.update(base_ctx)
    return render_response(request, "themes/%s/blog_article_detail.html" % (blog.theme), ctx)

def show_article_month_list(request, username, year, month):
    """
        显示某月内发布的所有文章
    """
    #显示公共信息
    member = get_object_or_404(User, username=username)
    blog = member.bloginfo
    base_ctx = get_base_context(member, blog)
    
    #显示分页后的文章
    current_page = utils.get_current_page(request)
    article_list = Article.objects.filter(blog=blog, created_date__year=year, created_date__month=month)
    # 获取分页信息
    pages_context = utils.get_pages_context(article_list, current_page, blog.display_count)
    articles = pages_context['page_current']
    articles_page_range = pages_context['page_range']
    
    #显示文章存档
    archives = Article.objects.filter(blog=blog).dates('created_date', 'month')
    year_list = get_different_years(archives)
    
    ctx = {'articles':articles, 'articles_page_range':articles_page_range,
           'archives':archives, 'year_list':year_list}
    ctx.update(base_ctx)
    return render_response(request, "themes/%s/blog_article_list.html" % (blog.theme), ctx)

def show_category(request, username, slug):
    #显示公共信息
    member = get_object_or_404(User, username=username)
    blog = member.bloginfo
    base_ctx = get_base_context(member, blog)
    
    #显示分类的详细信息
    category = get_object_or_404(Category, blog=blog, slug=slug)
    current_category = category.id
    root_category = category.get_root_category()
    
    #显示分类中所有的文章
    current_page = utils.get_current_page(request)
    article_list = category.article_set.filter(is_published=True)
    pages_context = utils.get_pages_context(article_list, current_page, blog.display_count)
    articles = pages_context['page_current']
    articles_page_range = pages_context['page_range']
    article_count = article_list.count()
    
    #显示文章存档
    archives = Article.objects.filter(blog=blog).dates('created_date', 'month')
    year_list = get_different_years(archives)
    
    ctx = {'category':category, 'articles':articles, 'articles_page_range':articles_page_range,
           'article_count':article_count, 'archives':archives, 'year_list':year_list,
            'current_category':current_category, 'root_category':root_category}
    ctx.update(base_ctx)
    return render_response(request, "themes/%s/blog_category_detail.html" % (blog.theme), ctx)

def post_comment(request, username, slug):
    if request.POST:
        nexturl = request.POST.get('nexturl')
        member = get_object_or_404(User, username=username)
        blog = member.bloginfo
        
        # 获取要评论的对象
        content_type = request.POST.get('content_type')
        app_label = content_type.split('.')[0]
        model_name = content_type.split('.')[1]
        class_name = get_model(app_label, model_name)
        model = class_name.objects.get(blog=blog, slug=slug)
        
        #保存评论内容
        form = CommentForm(model, data=request.POST)
        if form.is_valid():
            comment = form.get_comment_object()
            comment.ip_address = request.META.get("REMOTE_ADDR", None)
            comment.pertain = blog.id
            comment.save()
            return redirect(nexturl)
        
    return redirect(model.get_absolute_url() + "#comment-form")

def show_tag(request, username, id):
    """
        显示标签内所有的文章
    """
    member = get_object_or_404(User, username=username)
    blog = member.bloginfo
    base_ctx = get_base_context(member, blog)
    
    #显示分类中所有的文章
    current_page = utils.get_current_page(request)
    ctype = ContentType.objects.get_for_model(Article)
    tag_items = TaggedItem.objects.filter(tag=get_object_or_404(Tag, pk=id), content_type__pk=ctype.pk)
    article_list = [tag_item.content_object for tag_item in tag_items]
    pages_context = utils.get_pages_context(article_list, current_page, blog.display_count)
    articles = pages_context['page_current']
    articles_page_range = pages_context['page_range']
    
    #显示文章存档
    archives = Article.objects.filter(blog=blog).dates('created_date', 'month')
    year_list = get_different_years(archives)
    
    ctx = {'articles':articles, 'articles_page_range':articles_page_range,
           'archives':archives, 'year_list':year_list}
    ctx.update(base_ctx)
    return render_response(request, "themes/%s/blog_article_list.html" % (blog.theme), ctx)

def show_page(request, username, slug):
    member = get_object_or_404(User, username=username)
    blog = member.bloginfo
    base_ctx = get_base_context(member, blog)
    
    page = Page.objects.get(blog=blog, slug=slug)
    
    #发送评论后要跳转到的页面
    nexturl = page.get_absolute_url()
    
    ctx = {'page':page, 'nexturl':nexturl}
    ctx.update(base_ctx)
    return render_response(request, "themes/%s/page.html" % (blog.theme), ctx)

def user_login(request):
    if request.method == "POST":
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        next = request.GET.get('next', '')
        if login_post(request, username, password):
            if next:
                return HttpResponseRedirect(next)
            else:
                return HttpResponseRedirect('/admin/%s' % username)
    return render_response(request, "admin/login.html", None)

def user_logout(request):
    logout(request)
    return HttpResponseRedirect('/accounts/login')

def user_register(request):
    return render_response(request, "admin/register.html", None)

def get_different_years(archives):
    year_list = {}
    for archive in archives:
        year = archive.year
        if year_list.has_key(year) == False:
            year_list[year] = []
        month = MONTH_ALIAS[int(archive.month) - 1]
        year_list[year].append((archive.month, month))
#        if month not in year_list[year]:
#            year_list[year].append(month)
    return year_list

def get_base_context(member, blog):
    tags = Tag.objects.all()        #获取标签
    pages = Page.objects.filter(blog=blog)
    
    return locals()

#def search(request, username):
#    #显示公共信息
#    member = get_object_or_404(User, username=username)
#    blog = member.bloginfo
#    base_ctx = get_base_context(member, blog)
#    
#    keyword = request.GET.get("q")
#    results = search_process(keyword)
#    count = len(results)
#    
#    ctx = {'keyword':keyword, 'count':count, 'results':results}
#    ctx.update(base_ctx)
#    return render_response(request, "themes/%s/search_results.html" % (blog.theme), ctx)



